import Taro from '@tarojs/taro'

// HTTP请求状态码
const HTTP_STATUS = {
  SUCCESS: 200,
  CLIENT_ERROR: 400,
  AUTHENTICATE: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  SERVER_ERROR: 500,
  BAD_GATEWAY: 502,
  SERVICE_UNAVAILABLE: 503,
  GATEWAY_TIMEOUT: 504,
}

const taroDefaultRequest = {
  url: '',
  method: 'GET',
  dataType: 'json',
  responseType: 'text',
  header: {
    'content-type': 'application/json',
    Authorization: '',
    Accept: 'application/json',
  },
}

// const validateTokenName = 'token'

const packRequest = (
  newRequestObj: {
    url: string
    data: any
    method: 'GET' | 'OPTIONS' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' | undefined
    header: any
    dealLoginSelf: boolean
    dealErrorSelf:boolean
  }
) => {
  let response: any
  return Taro.request(newRequestObj)
    .then((resp: any) => {
      // handle HTTP_STATUS Code
      // console.log(resp)
      response = resp
      let errorMessage = ''
      let errorObj = { code: '', message: '' }
      switch (resp.statusCode) {
        case HTTP_STATUS.SUCCESS:
          if (typeof resp.data.code !== 'undefined') {
            switch (resp.data.code) {
              case 0:
                // 正常交互 不需要收集
                return resp.data.data
              default:
                errorObj = { ...resp.data }
                // Raven.captureException('未定义后端错误')
                break
            }
          }
        case HTTP_STATUS.CLIENT_ERROR:
          errorMessage = '客户端错误'
          // Raven.captureException(errorMessage)
          break
        case HTTP_STATUS.FORBIDDEN:
          errorMessage = '禁止请求'
          break
        case HTTP_STATUS.NOT_FOUND:
          errorMessage = '未发现服务, 请联系客服'
          console.error(newRequestObj, resp)
          break
        case HTTP_STATUS.SERVER_ERROR:
          errorMessage = '服务器问题, 请联系客服'
          console.error(newRequestObj, resp)
          break
        default:
          errorMessage = '未知问题，请联系客服'
          console.error(newRequestObj, resp)
          break
      }
      // 统一在catch中catch
      // Raven.captureException(errorMessage)
      if (errorMessage) {
        return Promise.reject(errorMessage)
      } else if (errorObj.code) {
        return Promise.reject(errorObj)
      }
    })
    .catch((e: any): any => {
      console.log('newRequestObj', newRequestObj)
      console.log('response', response)
      console.error(e, 'requesterror')
      // Raven.captureException({ requestError: e });
      // common error
      if(newRequestObj.dealErrorSelf){
        return Promise.reject(e)
      }
      else
      if (typeof e === 'string') {
        // Taro.showToast({title:e, icon:'error'})
        return Promise.reject(e)
      } else if (e instanceof Object) {
        return Promise.reject(e.message)
      }
      // Raven.captureMessage(e)
    })
}

const request = ({
  baseURL,
  url,
  data,
  method,
  absolute = false,
  dealLoginSelf = false,
  dealErrorSelf = false
}: {
  baseURL: string
  url: string
  data: any
  method: 'GET' | 'OPTIONS' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' | undefined
  auth: boolean
  absolute: boolean
  dealLoginSelf: boolean
  dealErrorSelf:boolean
}) => {
  const path = absolute ? url : baseURL + url
  const newRequestObj = {
    ...taroDefaultRequest,
    url: path,
    method,
    data,
    dealLoginSelf,
    dealErrorSelf
  }
  // 序列化get参数到url
  // if (method === 'GET') {
  //   const stringy = Qs.stringify(newRequestObj.data, {
  //     arrayFormat: 'brackets',
  //   })
  //   newRequestObj.url = `${newRequestObj.url}?${stringy}`
  //   newRequestObj.data = {}
  // }
  return packRequest(newRequestObj)
}

export default request
